package com.atguigu.gmall.seckill.listener;


import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.model.mq.to.seckill.SeckillMsg;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.seckill.biz.SeckillBizService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;


@Service
@Slf4j
public class SeckillOrderQueueListener {
    @Autowired
    RabbitService rabbitService;

    @Autowired
    SeckillBizService seckillBizService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConstant.QUEUE_SECKILL_QUEUE,durable = "true",
                    exclusive = "false",
                    autoDelete = "false"
            ),
            exchange = @Exchange(value = RabbitConstant.EXCHANGE_SECKILL_EVENT,
                    type = "topic",durable = "true"),
            key = RabbitConstant.RK_SECKILL_ORDER_QUEUE
    ))
    public void handle(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String msgStr = new String(message.getBody());
        try {
            //业务扣减库存
            SeckillMsg seckillMsg = JSONs.stringToObj(msgStr, SeckillMsg.class);
            log.info("秒杀排队单进入，准备扣减库存，单数据{}",msgStr);
            seckillBizService.updateStock(seckillMsg);
        } catch (Exception e) {
            e.printStackTrace();
            rabbitService.retry(deliveryTag, channel, msgStr, 5);
        }
    }
}
